import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { 
  SDTemplate, 
  TemplateResponse,
  UpdateTemplateRequest,
  DeleteTemplateResponse 
} from '@/types/templates';
import { validateTemplate, sanitizeTemplate } from '@/utils/templateValidation';

const COLLECTION_NAME = 'sd_templates';

interface RouteParams {
  params: {
    id: string;
  };
}

/**
 * GET /api/templates-db/[id]
 * 获取单个模板详情
 */
export async function GET(
  request: NextRequest,
  { params }: RouteParams
) {
  try {
    const { id } = params;
    
    if (!id) {
      return NextResponse.json({
        success: false,
        error: '模板ID不能为空'
      } as TemplateResponse, { status: 400 });
    }

    const db = await getDb();
    const result = await db.findOne<SDTemplate>(COLLECTION_NAME, { id });
    
    if (!result.success) {
      return NextResponse.json({
        success: false,
        error: result.error || '查询模板失败'
      } as TemplateResponse, { status: 500 });
    }

    if (!result.data) {
      return NextResponse.json({
        success: false,
        error: '模板不存在'
      } as TemplateResponse, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      data: result.data
    } as TemplateResponse);

  } catch (error: any) {
    console.error('获取模板详情失败:', error);
    return NextResponse.json({
      success: false,
      error: error.message || '服务器内部错误'
    } as TemplateResponse, { status: 500 });
  }
}

/**
 * PUT /api/templates-db/[id]
 * 更新模板
 */
export async function PUT(
  request: NextRequest,
  { params }: RouteParams
) {
  try {
    const { id } = params;
    
    if (!id) {
      return NextResponse.json({
        success: false,
        error: '模板ID不能为空'
      } as TemplateResponse, { status: 400 });
    }

    const body: UpdateTemplateRequest = await request.json();
    const { template } = body;

    if (!template) {
      return NextResponse.json({
        success: false,
        error: '更新数据不能为空'
      } as TemplateResponse, { status: 400 });
    }

    const db = await getDb();
    
    // 检查模板是否存在
    const existingResult = await db.findOne<SDTemplate>(COLLECTION_NAME, { id });
    if (!existingResult.success) {
      return NextResponse.json({
        success: false,
        error: existingResult.error || '查询模板失败'
      } as TemplateResponse, { status: 500 });
    }

    if (!existingResult.data) {
      return NextResponse.json({
        success: false,
        error: '模板不存在'
      } as TemplateResponse, { status: 404 });
    }

    // 合并现有数据和更新数据
    const mergedTemplate = {
      ...existingResult.data,
      ...template,
      id, // 确保ID不被更改
      created_at: existingResult.data.created_at, // 保持创建时间不变
      updated_at: new Date().toISOString() // 更新修改时间
    };

    // 数据清理和标准化
    const sanitizedTemplate = sanitizeTemplate(mergedTemplate);

    // 数据验证
    const validation = validateTemplate(sanitizedTemplate);
    if (!validation.isValid) {
      return NextResponse.json({
        success: false,
        error: '数据验证失败',
        details: validation.errors
      }, { status: 400 });
    }

    // 更新数据库
    const updateResult = await db.update<SDTemplate>(
      COLLECTION_NAME, 
      { id }, 
      sanitizedTemplate
    );
    
    if (!updateResult.success) {
      return NextResponse.json({
        success: false,
        error: updateResult.error || '更新模板失败'
      } as TemplateResponse, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      data: updateResult.data
    } as TemplateResponse);

  } catch (error: any) {
    console.error('更新模板失败:', error);
    return NextResponse.json({
      success: false,
      error: error.message || '服务器内部错误'
    } as TemplateResponse, { status: 500 });
  }
}

/**
 * DELETE /api/templates-db/[id]
 * 删除单个模板
 */
export async function DELETE(
  request: NextRequest,
  { params }: RouteParams
) {
  try {
    const { id } = params;
    
    if (!id) {
      return NextResponse.json({
        success: false,
        error: '模板ID不能为空'
      } as DeleteTemplateResponse, { status: 400 });
    }

    const db = await getDb();
    
    // 检查模板是否存在
    const existingResult = await db.findOne<SDTemplate>(COLLECTION_NAME, { id });
    if (!existingResult.success) {
      return NextResponse.json({
        success: false,
        error: existingResult.error || '查询模板失败'
      } as DeleteTemplateResponse, { status: 500 });
    }

    if (!existingResult.data) {
      return NextResponse.json({
        success: false,
        error: '模板不存在'
      } as DeleteTemplateResponse, { status: 404 });
    }

    // 删除模板
    const deleteResult = await db.delete(COLLECTION_NAME, { id });
    
    if (!deleteResult.success) {
      return NextResponse.json({
        success: false,
        error: deleteResult.error || '删除模板失败'
      } as DeleteTemplateResponse, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      message: `模板 "${existingResult.data.name}" 删除成功`
    } as DeleteTemplateResponse);

  } catch (error: any) {
    console.error('删除模板失败:', error);
    return NextResponse.json({
      success: false,
      error: error.message || '服务器内部错误'
    } as DeleteTemplateResponse, { status: 500 });
  }
}

/**
 * PATCH /api/templates-db/[id]
 * 部分更新模板（与PUT类似，但更明确表示部分更新）
 */
export async function PATCH(
  request: NextRequest,
  { params }: RouteParams
) {
  // 复用PUT逻辑
  return PUT(request, { params });
}